package com.youngball.web.controller.sys.web.controller;


import com.youngball.business.utill.ObjectNullUtils;
import com.youngball.shiro.entity.Resource;
import com.youngball.shiro.entity.Role;
import com.youngball.shiro.service.ResourceService;
import com.youngball.shiro.service.RoleService;
import com.youngball.web.controller.BaseController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**

 * <p>Version: 1.0
 */
@Controller
@RequestMapping("${adminPath}/role")
public class RoleController extends BaseController{

    @Autowired
    private RoleService roleService;

    @Autowired
    private ResourceService resourceService;
/*
    @RequiresPermissions("role:view")
    @RequestMapping(method = RequestMethod.GET)
    public String list(Model model) {
        model.addAttribute("roleList", roleService.findAll());
        return "role/list";
    }
*/
      // @RequiresPermissions("role:view")
    @RequestMapping(method = RequestMethod.GET,headers="Accept=application/json",value = "/roles")
    public ResponseEntity<?> list(Model model) {
                 Map maps=new HashMap();
                    List <Role> roles= roleService.findAll();
               if(roles.size()>0) {
                   maps.put("roles",roles);
                   return new ResponseEntity<Map>( maps, HttpStatus.OK);
           }
           maps.put("roles","没有角色");
           return new ResponseEntity<Map>( maps, HttpStatus.OK);
       }

    @RequestMapping(value = "roleList",method = RequestMethod.GET)
    public ResponseEntity<Map> roleList() {
        Map maps = new HashMap();
        try
        {
            List<Role> roles = roleService.findAll();
            for(Role user : roles)
            {
                List<Long> resources = user.getResourceIds();
                List<String> res = new ArrayList<String>();

                for(Long role : resources)
                {
                    Resource one = resourceService.findOne(role);
                    if(one == null) continue;
                    res.add(one.getName());
                }
                user.setResource(res);
            }

            maps.put("code","0");
            maps.put("msg", "获取成功");
            maps.put("data",roles);
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        maps.put("msg", "获取失败");
        maps.put("code", com.youngball.business.utill.Code.DEFAI.toString());
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }

    @RequestMapping(value = "roleDetail",method = RequestMethod.GET)
    public ResponseEntity<Map> roleList(Long id) {
        Map maps = new HashMap();
        try
        {
            Role roles = roleService.findOne(id);
            List<Long> resources = roles.getResourceIds();
            List<String> res = new ArrayList<String>();

            for(Long role : resources)
            {
                Resource one = resourceService.findOne(role);
                if (ObjectNullUtils.isNotBlank(one)) {
                    res.add(one.getName());
                }
            }
            roles.setResource(res);

            maps.put("code","0");
            maps.put("msg", "获取成功");
            maps.put("data",roles);
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        maps.put("msg", "获取失败");
        maps.put("code", com.youngball.business.utill.Code.DEFAI.toString());
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }

    //@RequiresPermissions("role:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String showCreateForm(Model model) {
        setCommonData(model);
        model.addAttribute("role", new Role());
        model.addAttribute("op", "新增");
        return "role/edit";
    }

    @RequiresPermissions("role:create")
    @RequestMapping(method = RequestMethod.POST,headers="Accept=application/json",value = "roles")
    public ResponseEntity<?> create(Role role, RedirectAttributes redirectAttributes) {
        Map maps=new HashMap();
        try {
            if(!ObjectNullUtils.isNotBlank(role.getRole())){
                maps.put("code","1");
                maps.put("msg", "请输入角色名");
                return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
            }
            roleService.createRole(role);
        }catch (Exception e){
            maps.put("roles", "增加角色失败" + e.getMessage());
            return new ResponseEntity<Map>( maps, HttpStatus.OK);
        }
        maps.put("roles","增加角色成功");
        return new ResponseEntity<Map>( maps, HttpStatus.OK);

    }

    @RequestMapping(value = "createRole",method = RequestMethod.POST)
    public ResponseEntity<Map> createRole(@RequestBody Role role) {
        Map maps = new HashMap();
        try
        {
            roleService.createRole(role);
            maps.put("code","0");
            maps.put("msg", "增加成功");
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        maps.put("msg", "获取失败");
        maps.put("code", com.youngball.business.utill.Code.DEFAI.toString());
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }

    //@RequiresPermissions("role:update")
    @RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
    public String showUpdateForm(@PathVariable("id") Long id, Model model) {
        setCommonData(model);
        model.addAttribute("role", roleService.findOne(id));
        model.addAttribute("op", "修改");
        return "role/edit";
    }

    // @RequiresPermissions("role:update")
    @RequestMapping(value = "/{id}/roles", method = RequestMethod.PUT,headers="Accept=application/json")
    public ResponseEntity<?> update(Role role, RedirectAttributes redirectAttributes) {

        Map maps=new HashMap();
        try {
            roleService.updateRole(role);
        }catch (Exception e){
            maps.put("roles", "修改角色失败" + e.getMessage());
            return new ResponseEntity<Map>( maps, HttpStatus.OK);
        }
        maps.put("roles","修改角色成功");
        return new ResponseEntity<Map>( maps, HttpStatus.OK);

    }

    @RequestMapping(value = "updateRole",method = RequestMethod.POST)
    public ResponseEntity<Map> updateRole(@RequestBody Role role) {
        Map maps = new HashMap();
        try
        {
            Role local = roleService.findOne(role.getId());
            if("admin".equals(local.getRole()) && ("admin").equals(role.getRole()))
            {
                maps.put("msg", "不能修改系统管理员用户名");
                maps.put("code", com.youngball.business.utill.Code.DEFAI.toString());
                return new ResponseEntity<Map>( maps, HttpStatus.OK);
            }
            if(role.getRole()!=null && !role.getRole().equals(local.getRole())){
                Role role1 = roleService.findByName(role.getRole());
                if(ObjectNullUtils.isNotBlank(role1)){
                    maps.put("msg", "已存在该角色名");
                    maps.put("code", com.youngball.business.utill.Code.DEFAI.toString());
                    return new ResponseEntity<Map>( maps, HttpStatus.OK);
                }
            }

            if(role.getDescription() != null) local.setDescription(role.getDescription());
            if(role.getResourceIds() != null) local.setResourceIds(role.getResourceIds());
            if(role.getRole() != null) local.setRole(role.getRole());
            roleService.updateRole(local);
            maps.put("code","0");
            maps.put("msg", "更新成功");
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        maps.put("msg", "获取失败");
        maps.put("code", com.youngball.business.utill.Code.DEFAI.toString());
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }

    //@RequiresPermissions("role:delete")
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    public String showDeleteForm(@PathVariable("id") Long id, Model model) {
        setCommonData(model);
        model.addAttribute("role", roleService.findOne(id));
        model.addAttribute("op", "删除");
        return "role/edit";
    }

    //@RequiresPermissions("role:delete")
    @RequestMapping(value = "/{id}/roles", method = RequestMethod.DELETE,headers="Accept=application/json")
    public ResponseEntity<?> delete(@PathVariable("id") Long id) {

        Map maps=new HashMap();
        try {
            roleService.deleteRole(id);
        }catch (Exception e){
            maps.put("roles", "删除角色失败" + e.getMessage());
            return new ResponseEntity<Map>( maps, HttpStatus.OK);
        }
        maps.put("roles", "删除角色成功");
        return new ResponseEntity<Map>( maps, HttpStatus.OK);
    }

    @RequestMapping(value = "deleteRole/{id}",method = RequestMethod.POST)
    public ResponseEntity<Map> deleteRole(@PathVariable Long id) {
        Map maps = new HashMap();
        try
        {
            Role local = roleService.findOne(id);
            if("admin".equals(local.getRole())) {
                maps.put("msg", "不能删除系统管理员");
                maps.put("code", com.youngball.business.utill.Code.DEFAI.toString());
                return new ResponseEntity<Map>( maps, HttpStatus.OK);
            }
            roleService.deleteRole(id);
            maps.put("code","0");
            maps.put("msg", "删除成功");
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        maps.put("msg", "获取失败");
        maps.put("code", com.youngball.business.utill.Code.DEFAI.toString());
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }

    private void setCommonData(Model model) {
        model.addAttribute("resourceList", resourceService.findAll());
    }

}
